package com.jzit168.library_retrofit.interceptors

import android.util.Log
import com.jzit168.library_common.common.API.IP
import com.jzit168.library_common.common.Constant
import com.jzit168.library_retrofit.RetrofitFactory
import com.jzit168.library_retrofit.api.RetrofitService
import com.jzit168.library_retrofit.common.APICode
import com.jzit168.library_retrofit.common.JzResult
import com.jzit168.library_utils.LogUtil
import com.jzit168.library_utils.MMKVUtil
import com.zero.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import kotlin.text.Charsets.UTF_8


/**
 *@Desc: 携带token的拦截器
 *@Author: Android Developer
 *@Date: 2020/10/15
 *
 **/
class TokenInterceptor(private val token: String) : Interceptor {

    companion object {
        private const val TAG = "TokenInterceptor"
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        Log.e(TAG, "intercept: token:$token")
        val request = chain.request().newBuilder()
        request.addHeader("Authorization", "Bearer $token")
        val response = chain.proceed(request.build())
        try {
            if (response.isSuccessful) {
                Log.e(TAG, "intercept: 不需要刷新请求:${response.isSuccessful}")
                return response
            } else {
                val responseBody = response.body
                val source = responseBody?.source()
                source?.request(Long.MAX_VALUE)
                val buffer = source?.buffer
                val string = buffer?.clone()?.readString(UTF_8)
                val result = Gson().fromJson(string.toString(), JzResult::class.java)
                return when (result.code) {
                    APICode.REFRESH -> {
                        Log.e(TAG, "intercept: 刷新请求")
                        response.close()
                        val newToken = refresh()
                        val newRequest = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer $newToken")
                            .build()
                        chain.proceed(newRequest)
                    }
                    else -> {
                        Log.e(TAG, "intercept: 不需要刷新请求")
                        response
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return response
    }

    @Synchronized
    private fun refresh(): String? {
        //通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        var newToken: String? = null
        val retrofit =
            RetrofitFactory.create(IP, RetrofitService::class.java)
        try {
            val call = retrofit.refresh()
            //call.execute是同步方法 call.enqueue是异步方法
            call.execute().also {
                if (it.isSuccessful) {
                    val body = it.body()
                    if (body != null) {
                        val data = body.data
                        MMKVUtil.setString(Constant.TOKEN, data.access_token)
                        MMKVUtil.setString(Constant.REFRESHTOKEN, data.refresh_token)
                        newToken = data.access_token
                    }
                } else {
                    LogUtil.e("刷新失败重新登录1")
                }
            }
        } catch (e: Exception) {
            LogUtil.e("刷新失败重新登录2")
        }
        return newToken
    }
}